package com.example.demo.service.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.mapper.FundAccountMapper;
import com.example.demo.mapper.TransferRecordMapper;
import com.example.demo.mapper.UserCompetitionMapper;
import com.example.demo.mapper.UserFundAccountMapper;
import com.example.demo.pojo.Accounts.FundAccounts;
import com.example.demo.pojo.Accounts.TransferRecord;
import com.example.demo.pojo.Accounts.UserFundAccounts;
import com.example.demo.pojo.Competitions.UserCompetitions;
import com.example.demo.pojo.R;
import com.example.demo.service.UserAccountService;
import com.example.demo.utils.CompetitionUtils;
import com.example.demo.utils.TokenUtil.decryptToken;
import com.example.demo.utils.TokenUtil.spiltUtils;
import com.example.demo.utils.UserUtil;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import static com.example.demo.utils.ConstantUtils.FINISH;

@Service
public class UserAccountServiceImpl extends ServiceImpl<UserFundAccountMapper, UserFundAccounts> implements UserAccountService {
    @Resource
    private UserFundAccountMapper userFundAccountMapper;

    @Resource
    private FundAccountMapper fundAccountsMapper;

    @Resource
    private TransferRecordMapper transferRecordMapper;

    @Resource
    private UserCompetitionMapper userCompetitionMapper;

    @Resource
    private CompetitionUtils competitionUtils;
    @Resource
    private UserUtil userUtil;


    @Override
    @Transactional
    public R<T> userTransferOfFunds(String token, Integer id, BigDecimal transferFunds) {
        //获取当前用户的id
        String decrypt = decryptToken.decrypt(token);
        String userName = spiltUtils.getUserName(decrypt);
        Integer userId = userUtil.getUserId(userName);
        boolean competitionStatus = competitionUtils.getCompetitionStatus(id, FINISH);
        if (!competitionStatus) {
            return R.failed("比赛已近截止");
        }
        //判断是否实名
        boolean realNameAuthentication = userUtil.getRealNameAuthentication(userId);
        if (!realNameAuthentication) {
            return R.failed("你还未进行实名认证！");
        }
        //判断用户是否退赛
        QueryWrapper<UserCompetitions> userCompetitionsQueryWrapper = new QueryWrapper<>();
        userCompetitionsQueryWrapper
                .eq("user_id", userId)
                .eq("competition_id", id)
                .eq("real_name", userUtil.getRealName(userName))
                .eq("status", "退赛");
        UserCompetitions userCompetitions = userCompetitionMapper.selectOne(userCompetitionsQueryWrapper);
        if (userCompetitions != null) {
            return R.failed("你已经退赛，无权操作账户!");
        }
        //查询当前用户银行账户
        QueryWrapper<UserFundAccounts> userFundAccountsQueryWrapper = new QueryWrapper<>();
        userFundAccountsQueryWrapper
                .eq("user_id", userId)
                .eq("user_account_id", id);
        UserFundAccounts userFundAccounts = userFundAccountMapper.selectOne(userFundAccountsQueryWrapper);
        //查询当前用户平台账户
        QueryWrapper<FundAccounts> fundAccountsQueryWrapper = new QueryWrapper<>();
        fundAccountsQueryWrapper
                .eq("user_id", userId)
                .eq("account_id", id);
        FundAccounts fundAccounts = fundAccountsMapper.selectOne(fundAccountsQueryWrapper);
        //转账操作
        TransferRecord transferRecord = new TransferRecord();
        transferRecord.setSequenceNumber(userId);
        // 1.银行账户转出
        UpdateWrapper<UserFundAccounts> userFundAccountsUpdateWrapper = new UpdateWrapper<>();
        // 判断账户是否有钱
        if (userFundAccounts.getUserTotalAsset().compareTo(transferFunds) < 0) {
            return R.failed("账户余额不足！");
        }
        // 减少总资产
        userFundAccounts.setUserTotalAsset(userFundAccounts.getUserTotalAsset().subtract(transferFunds));
        // 设置可用资金为更新后的总资产
        userFundAccounts.setAvailableFund(userFundAccounts.getUserTotalAsset());
        userFundAccounts.setUserAccountId(id);
        userFundAccounts.setUserId(userId);
        userFundAccounts.setUserBankAccount("银行账户");
        int userFundAccountUpdate = userFundAccountMapper.update(userFundAccounts, userFundAccountsUpdateWrapper);
        //记录转出账户id以及转出金额
        transferRecord.setOutgoingAccountId(userFundAccounts.getUserAccountId());
        transferRecord.setTransferTime(new Date());
        transferRecord.setOutgoingAmount(transferFunds);
        // 2.平台账户转入
        UpdateWrapper<FundAccounts> updateWrapper = new UpdateWrapper<>();
        // 先判断账户总金额是否为0
        if (fundAccounts.getTotalAsset().compareTo(BigDecimal.ZERO) == 0) {
            fundAccounts.setTotalAsset(transferFunds);
            fundAccounts.setAvailableFund(transferFunds);
        } else {
            // 如果账户总金额不为0，则只需增加转账金额
            fundAccounts.setTotalAsset(fundAccounts.getTotalAsset().add(transferFunds));
            fundAccounts.setAvailableFund(fundAccounts.getAvailableFund().add(transferFunds));
        }
        // 设置其他账户信息
        fundAccounts.setAccountId(id);
        fundAccounts.setUserId(userId);
        fundAccounts.setBankAccount("股票账户");
        // 执行更新操作
        int fundAccountUpdate = fundAccountsMapper.update(fundAccounts, updateWrapper);
        transferRecord.setIncomingAccountId(fundAccounts.getAccountId());
        transferRecord.setIncomingAmount(transferFunds);
        transferRecord.setExchangeRate(BigDecimal.ONE);
        // 检查是否成功更新账户信息
        boolean isUpdateSuccessful = fundAccountUpdate > 0 && userFundAccountUpdate > 0;
        if (isUpdateSuccessful) {
            //保存转账记录
            transferRecordMapper.insert(transferRecord);
            return R.success("转账成功！");
        }

        return R.failed("转账失败！");


    }

    @Override
    @Transactional
    public R<T> setUserFundAccount(String token, BigDecimal accounts, int id) {
        //获取当前用户的id
        String decrypt = decryptToken.decrypt(token);
        String userName = spiltUtils.getUserName(decrypt);
        Integer userId = userUtil.getUserId(userName);
        boolean competitionStatus = competitionUtils.getCompetitionStatus(id, FINISH);
        if (!competitionStatus) {
            return R.failed("比赛已近截止");
        }
        //判断是否实名
        boolean realNameAuthentication = userUtil.getRealNameAuthentication(userId);
        if (!realNameAuthentication) {
            return R.failed("你还未进行实名认证！");
        }
        //判断用户是否退赛
        QueryWrapper<UserCompetitions> userCompetitionsQueryWrapper = new QueryWrapper<>();
        userCompetitionsQueryWrapper
                .eq("user_id", userId)
                .eq("competition_id", id)
                .eq("real_name", userUtil.getRealName(userName))
                .eq("status", "退赛");
        UserCompetitions userCompetitions = userCompetitionMapper.selectOne(userCompetitionsQueryWrapper);
        if (userCompetitions != null) {
            return R.failed("你已经退赛，无权操作账户!");
        }

        //根据用户的id查询用户银行账户信息
        QueryWrapper<UserFundAccounts> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId).eq("user_account_id", id);
        UserFundAccounts existingAccount = userFundAccountMapper.selectOne(queryWrapper);

        if (existingAccount == null) {
            // 如果账户不存在，插入新记录
            return R.failed("账户不存在！");
        } else {
            // 如果账户存在，更新记录
            UpdateWrapper<UserFundAccounts> userFundAccountUpdateWrapper = new UpdateWrapper<>();
            userFundAccountUpdateWrapper.eq("user_id", userId).eq("user_account_id", id);
            UserFundAccounts updateUserFundAccount = new UserFundAccounts();
            updateUserFundAccount.setUserAccountId(id);
            updateUserFundAccount.setUserId(userId);
            updateUserFundAccount.setUserBankAccount("银行账户");
            updateUserFundAccount.setUserTotalAsset(accounts);
            updateUserFundAccount.setAvailableFund(accounts);
            int update = userFundAccountMapper.update(updateUserFundAccount, userFundAccountUpdateWrapper);
            if (update > 0) {
                return R.success("账户更新成功！");
            }
        }
        return R.failed("设置失败！");
    }

    @Override
    public R<List<UserFundAccounts>> getUserAccount(Integer id, String token) {
        //获取当前用户的id
        String decrypt = decryptToken.decrypt(token);
        String userName = spiltUtils.getUserName(decrypt);
        Integer userId = userUtil.getUserId(userName);
        //判断比赛是否结束
        boolean competitionStatus = competitionUtils.getCompetitionStatus(id, FINISH);
        if (!competitionStatus) {
            return R.failed("比赛已经截止");
        }
        //判断是否实名
        boolean realNameAuthentication = userUtil.getRealNameAuthentication(userId);
        if (!realNameAuthentication) {
            return R.failed("你还未进行实名认证！");
        }
        //判断用户是否退赛
        QueryWrapper<UserCompetitions> userCompetitionsQueryWrapper = new QueryWrapper<>();
        userCompetitionsQueryWrapper
                .eq("user_id", userId)
                .eq("competition_id", id)
                .eq("real_name", userUtil.getRealName(userName))
                .eq("status", "退赛");
        UserCompetitions userCompetitions = userCompetitionMapper.selectOne(userCompetitionsQueryWrapper);
        if (userCompetitions != null) {
            return R.failed("你已经退赛，无权操作账户!");
        }
        //根据用户的id查询用户银行账户信息
        QueryWrapper<UserFundAccounts> userFundAccountQueryWrapper = new QueryWrapper<>();
        //当前用户账户信息
        QueryWrapper<UserFundAccounts> userFundAccountList = userFundAccountQueryWrapper
                .eq("user_id", userId)
                .eq("user_account_id", id);
        List<UserFundAccounts> userFundAccounts = userFundAccountMapper.selectList(userFundAccountList);
        return R.success(userFundAccounts);
    }


}
